'''
Created on 2013-6-5

@author: LJ
'''
import web
import funcs
import model
import json, time
from owlparse import ogtxml

web.config.debug = False

urls = (
    '/', 'Index',
    '/search', 'Search',
    '/admin', 'Admin',
    '/users', 'Users',
    '/account/signin', 'Signin',
    '/account/signup', 'Signup',
    '/account/myknows', 'Myknows',
    '/account/settings', 'Settings',
    '/account/logout', 'Logout',
    '/account/profile', 'Profile',
    '/about/aboutus', 'Aboutus',
    '/about/programs', 'Programs',
    '/about/team','Team',
    '/about/contact','Contact',
    '/myogr', 'Myogr',
    '/test', 'Test',
    '/knowledgeman', 'Knowledgeman',
    '/resourceman', 'Resourceman',
    '/knowsame', 'Knowsame',
    '/contents', 'Contents',
    '/content', 'Content',
    '/reuse', 'Reuse',
    '/point', 'Point',
    '/history', 'History',
    '/errpage', 'Errpage',
)

app = web.application(urls, globals())
#session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'uid': 1, 'udata':{'fullname':'jianglei'}})
session = web.session.Session(app, web.session.DiskStore('sessions'))

t_globals = {
    'tempfuns': funcs.tempfuns,
    'session': session
}

render = web.template.render('templates', base='base', globals=t_globals)

class AuthManage:
    @staticmethod
    def befLogin():
        if not session.has_key('uid'):
            raise web.seeother("/account/signin")

class Index:
    def GET(self):
        return render.index()

class Admin:
    def GET(self):
        return render.admin(ogtxml)
    def POST(self):
        info = web.input()
        if info.type == "knowledge":
            if info.knowledge not in ogtxml.knowledges2:
                return render.admin(ogtxml)
            else:
                raise web.seeother("/knowledgeman?type="+info.knowledge)
        elif info.type == "resource":
            if info.resource not in ogtxml.resources2:
                return render.admin(ogtxml)
            else:
                raise web.seeother("/resourceman?type="+info.resource)
    
class Knowledgeman:
    def GET(self):
        AuthManage.befLogin()
        info = web.input(type="default")
        if info.type not in ogtxml.knowledges2:
            raise web.seeother("/admin")
        else:
            return render.knowledgeman(ogtxml, info.type)
    def POST(self):
        #Skip the resource in the form of files uploaded
        AuthManage.befLogin()
        info = web.input(Imageresource={},Videoresource={},Audioresource={})
        if info.lev1 == "1":
            if info.knowid == "0":
                re = model.db.select('knows', where=" knowledge=$info.know and name=$info.Name ", vars=locals())
                if bool(re):
                    knowid = re[0].get('id')
                else:
                    inset = {'knowledge':info.know , 'name': info.Name, 'version':0}
                    knowid = model.db.multiple_insert('knows', values = [inset])[0]
            else:
                knowid = int(info.knowid)
            kid = model.db.multiple_insert(info.know, [funcs.knowledgedbdata(info.know, knowid, info, session['uid'])])[0]
            model.db.update('knows', where="id=$knowid", version=kid, vars=locals())
            funcs.allResourcedbdata(kid, info, session['uid'])
            raise web.seeother("/content?type="+info.know+"&kid="+str(kid))

class Reuse:
    def GET(self):
        AuthManage.befLogin()
        info = web.input(type="Process", kid='1')
        re = model.db.select(info.type, where=" id=$info.kid ", vars=locals())
        if bool(re):
            kinfo = re[0]
            knowinfo = model.db.select("knows", where=" id=$kinfo.knowid ", vars=locals())[0]
            resinfo = funcs.getAllRes(info.type, info.kid)
            return render.reuse(ogtxml, knowinfo, kinfo, resinfo)
        else:
            raise web.seeother("/reuse")
    def POST(self):
        AuthManage.befLogin()
        info = web.input(Imageresource={},Videoresource={},Audioresource={})
        if info.lev1 == "1":
            knowid = int(info.knowid)
            kid = model.db.multiple_insert(info.know, [funcs.knowledgedbdata(info.know, knowid, info, session['uid'])])[0]
            model.db.update('knows', where="id=$knowid", version=kid, vars=locals())
            funcs.allResourcedbdataReuse(kid, info, session['uid'])
            raise web.seeother("/content?type="+info.know+"&kid="+str(kid))

class Knowsame:
    def POST(self):
        info = web.input(type="default")
        if info.type == "1":
            re = model.db.select('knows', what="id,name", where=" knowledge=$info.knowledge ", vars=locals())
            dat = []
            for i in re:
                dat.append(i)
            web.header('Content-Type','text/json')
            return json.dumps({'err':0, 'data':dat})
        elif info.type == "2":
            inset = {'knowledge':info.knowledge , 'name1': info.name1, 'name2': info.name2}
            samid = model.db.multiple_insert('knowsame', values = [inset])[0]
            web.header('Content-Type','text/json')
            return json.dumps({'err':0, 'data':samid})
            
    
class Resourceman:
    def GET(self):
        info = web.input(type="default")
        if info.type not in ogtxml.resources2:
            raise web.seeother("/admin")
        else:
            return render.resourceman(ogtxml, info.type)

class Aboutus:
    def GET(self):
        return render.aboutus()
class Programs:
    def GET(self):
        return render.programs()
class Team:
    def GET(self):
        return render.team()
class Contact:
    def GET(self):
        return render.contact()


class Signin:
    def GET(self):
        return render.signin()
    def POST(self):
        info = web.input(email="")
        re = model.db.select("users", where=" email=$info.email and pass=$info.password ", vars=locals())
        res = {'err':0, 'data':0}
        if bool(re):
            session.udata = re[0]
            uid = session.udata.id
            res['data'] = uid
            session.uid = uid
        web.header('Content-Type','text/json')
        return json.dumps(res)
        

class Signup:
    def GET(self):
        return render.signup(0)
    def POST(self):
        info = web.input()
        re = model.db.select("users", where=" email=$info.email ", vars=locals())
        if bool(re):
            return render.signup(1)
        else:
            inset = {'email':info.email, 'pass':info.password , 'fullname':info.name , 'register_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), 'authority':1}
            uid = model.db.multiple_insert('users', values=[inset])[0]
            session.uid = uid
            re = model.db.select("users", where=" id=$uid ", vars=locals())
            session.udata = re[0]
            raise web.seeother("/users?i="+str(uid))

class Users:
    def GET(self):
        info = web.input(i="1")
        userid = int(info.i)
        re = model.db.select("users", where=" id=$userid ", vars=locals())
        if bool(re):
            userdata = re[0]
            myknows = funcs.getMykonws(userid)
            print userdata
            return render.users( userdata, myknows )
        else:
            raise web.seeother("/errpage")


class Profile:
    def GET(self):
        AuthManage.befLogin()
        return render.profile()

class Myknows:
    def GET(self):
        AuthManage.befLogin()
        uid = session['uid']
        myknows = funcs.getMykonws(uid);
        myactivs = funcs.getMyPoints(uid)
        print myactivs
        return render.myknows(myknows, myactivs)

class Settings:
    def GET(self):
        AuthManage.befLogin()
        return render.settings()

class Logout:
    def GET(self):
        AuthManage.befLogin()
        session.kill()
        raise web.seeother("/")

class Myogr:
    def GET(self):
        return render.myogr()
    
class Contents:
    def GET(self):
        info = web.input(search="",type="",sortby="last" )
        if info.sortby == "last":
            order = "id ASC"
        else:
            order = "id DESC"
        whe = "version != 0 "
        if info.search != "":
            whe += " and name like '%"+info.search+"%' "
        if info.type != "":
            info.type = info.type.split(",")
            knows = model.db.select('knows', where=whe+"and knowledge in $info.type" ,order=order , limit=50, vars=locals())
        else:
            info.type = []
            knows = model.db.select('knows', where=whe ,order=order , limit=50, vars=locals())
        knows = funcs.select2list(knows)
        temp = funcs.handleknows(knows)
        kdetail = funcs.handleknowsdetail(temp)
        knows = funcs.addKnowsKey(knows)
        return render.contents(ogtxml, knows, kdetail, info)
    
class Content:
    def GET(self):
        info = web.input(type="Process", kid='3')
        re = model.db.select(info.type, where=" id=$info.kid ", vars=locals())
        if bool(re):
            kinfo = re[0]
            knowinfo = model.db.select("knows", where=" id=$kinfo.knowid ", vars=locals())[0]
            resinfo = funcs.getAllRes(info.type, info.kid)
            return render.content(ogtxml, knowinfo, kinfo, resinfo)
        else:
            raise web.seeother("/content")
        
class History:
    def GET(self):
        info = web.input(type="Process", name="DDE")
        re = model.db.select("knows", where=" knowledge=$info.type and name=$info.name ", vars=locals())
        if bool(re):
            knows = re[0]
            his = model.db.select(info.type, where="knowid=$knows.id",order="id DESC", limit=20, vars=locals())
            return render.history(knows, his)
        else:
            raise web.seeother("/history")
        
class Point:
    def POST(self):
        info = web.input()
        if session.has_key('uid'):
            funcs.pointdbdata(info, session['uid'])
            web.header('Content-Type','text/json')
            return json.dumps({'err':0,'data':'insert ok'})
        else:
            web.header('Content-Type','text/json')
            return json.dumps({'err':1,'data':'You must login in first!'})

class Search:
    def POST(self):
        info = web.input(type="1", search="b")
        if info.type == "1":
            whe = " name like '%"+info.search+"%' "
            knows = model.db.select('knows', where=whe ,order="id DESC" , limit=10, vars=locals())
            knows = funcs.select2list(knows)
            temp = funcs.handleknows_input(knows)
            print temp
            web.header('Content-Type','text/json')
            return json.dumps({'err':0,'data':temp})

class Errpage:
    def GET(self):
        return render.errpage()

class Test:
    def GET(self):
        return render.test()


if __name__ == '__main__':
    app.run()